import Home from "@/pages/home/home";
import IndexPage from "@/pages/index/index";
import Login from "@/pages/login/login";
import NotFound from "@/pages/notfound/notfound";
import { IStore } from "@/store";
import React, { lazy, Suspense, useEffect, useState } from "react";
import { shallowEqual, useSelector } from "react-redux";
import {
  Navigate,
  RouteObject,
  useLocation,
  useNavigate,
  useRoutes,
} from "react-router-dom";
import { Alert, Spin } from "antd";

// 匹配所有的路由 根据URL返回对应的路由
function LazyLoad(url: string) {
  // @ts-ignore
  const File = import.meta.glob<React.JSX>("../pages/**/*.tsx");
  const path = `../${url}.tsx`;
  const Modal = lazy(File[path]);
  return (
    <Suspense
      fallback={
        <Spin className="mt-80" tip="Loading..." delay={500}>
          <Alert
            message="请求数据中.."
            description="根据您网络的速度..."
            type="info"
          />
        </Spin>
      }
    >
      <Modal></Modal>
    </Suspense>
  );
}
let routes: RouteObject[] = [
  {
    path: "/",
    element: <Navigate to="/login"></Navigate>,
  },
  {
    path: "/home",
    element: <Home></Home>,
    children: [
      {
        path: "/home",
        element: <Navigate to="/home/index"></Navigate>,
      },
      {
        path: "/home/index",
        element: <IndexPage></IndexPage>,
      },
    ],
  },
  {
    path: "/login",
    element: <Login></Login>,
  },
  {
    path: "*",
    element: <NotFound></NotFound>,
  },
];
const RC: RouteObject[] = [
  {
    path: "/home/index",
    element: <IndexPage></IndexPage>,
  },
];
export default function () {
  const store = useSelector((state: IStore) => state.user, shallowEqual);
  const [filter, SetfilterData] = useState<any[]>(routes);
  const _ = useLocation();
  const navigate = useNavigate();
  useEffect(() => {
    routes[1].children = [...RC];
    if (store.menu.length > 0) {
      store.menu.forEach((item) => {
        item.children?.forEach((itemy: any) => {
          if (itemy.key.includes("/home")) {
            const obj: RouteObject = {
              path: itemy.key,
              element: LazyLoad(itemy.file),
            };
            const _ = routes[1].children?.find((item) => {
              return item.path == obj.path;
            });
            !_ && routes[1].children?.push(obj);
          } else {
            routes.splice(3, 0, {
              path: itemy.key,
              element: LazyLoad(itemy.file),
            });
          }
        });
      });
      navigate(_.pathname + _.search);
    }
    SetfilterData(routes);
  }, [store.menu]);

  return <>{useRoutes(filter)}</>;
}
